package com.situ.storehouse.controller;

import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.storehouse.util.ImageUtil;


@WebServlet("/image")
public class ImageController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//返回值类型为image图片
		response.setContentType("image/jepg");
		//禁止图片缓存
		response.setHeader("parama", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ServletOutputStream sos=response.getOutputStream();
		//随机生成一个四位字符串
		String str=randomString(4);
		ImageIO.write(ImageUtil.image(str), "JPEG", sos);//流写出图像
	   //将验证码存入session
		request.getSession().setAttribute("captcha", str);
		//释放资源
		sos.flush();
		sos.close();
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	//生成验证码,随机生成字符串，可指定长度
	public String randomString(int length) {
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=1;i<=length;i++) {
			int number=random.nextInt(4);//随机生成一个[0,4)的数
			long result=0;
			switch(number) {
			case 0://生成一个小写英文字母
				result=Math.round(Math.random()*25+65);
				sb.append(String.valueOf((char)result));
				break;
			case 1://生成一个大写英文字母
				result=Math.round(Math.random()*25+97);
				sb.append(String.valueOf((char)result));
				break;
				//生成一个0~9的数字
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			case 3:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}
}
